/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"shop/global"
)

type IRolesDepts interface {
	InsertRolesDepts() (int64, error)
	DeleteRolesDepts(roleId int64) error
	UpdateRolesDepts() error
	FindRolesDeptsList() (interface{}, error)
	SplitPageRolesDeptsList(pageIndex int64, pageSize int64) (interface{}, error)
}

/**
	RolesDepts实体对象
 **/
type RolesDepts struct {
	RoleId int64 `json:"role_id" gorm:"primary_key"` //

	DeptId int64 `json:"dept_id"` //
}

func (vo *RolesDepts) InsertRolesDepts() (int64, error) {
	table := global.GDB.Table("roles_depts")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.RoleId, nil
}

func (vo *RolesDepts) DeleteRolesDepts(roleId int64) error {
	table := global.GDB.Table("roles_depts")
	table = table.Where("role_id = ?", roleId)
	if err := table.Delete(RolesDepts{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *RolesDepts) UpdateRolesDepts() error {

	table := global.GDB.Table("roles_depts")
	table = table.Where("role_id = ?", vo.RoleId)
	if err := table.Updates(map[string]interface{}{
		"role_id": vo.RoleId, "dept_id": vo.DeptId}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *RolesDepts) FindRolesDeptsList() ([]RolesDepts, error) {
	var lists []RolesDepts
	table := global.GDB.Table("roles_depts")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *RolesDepts) SplitPageRolesDeptsList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []RolesDepts
	var total int64
	table := global.GDB.Table("roles_depts")
	table = table.Select("  role_id,   dept_id   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}
